//
//  VideoViewController.m
//  BeanTrip
//
//  Created by houlei on 15/7/8.
//  Copyright (c) 2015年 PandaGroup. All rights reserved.
//

#import "VideoViewController.h"
#import "VideoModel.h"
#import "VideoCollectionViewCell.h"
#import "MJRefresh.h"
#import "AFNetworking.h"
#import "HTTPTool.h"
#import "VideoWebViewController.h"
#define WIDTH ([UIScreen mainScreen].bounds.size.width)
#define HEIGHT ([UIScreen mainScreen].bounds.size.height)
@interface VideoViewController ()

@end

@implementation VideoViewController

/*
 @property (nonatomic,retain)MBProgressHUD *HUD;
 @property (nonatomic,assign)NSInteger pageNo;
 @property (nonatomic,retain)NSMutableArray *videoArray;
 @property (nonatomic,assign)BOOL isUpLoading;
 @property (nonatomic,retain)UICollectionView *collectionView;
 @property (nonatomic,assign)NSInteger next_Page;
 */
- (void)dealloc
{
    [_HUD release];
    [_videoArray release];
    [_collectionView release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor cyanColor];
    
    self.videoArray = [NSMutableArray array];
    self.isUpLoading = NO;
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64 - 49) collectionViewLayout:flowLayout];
    //设置item的大小
    flowLayout.itemSize = CGSizeMake(WIDTH-10, WIDTH/3/16*9+10);
    //设置每行item的间隔
    flowLayout.minimumLineSpacing = 20;
    //设置每列item的间隔
    flowLayout.minimumInteritemSpacing = 10;
    //设置滚动方向
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    //设置item各边的距离(上左下右)
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectionView];
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    //注册cell
    [self.collectionView registerClass:[VideoCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    
    //上啦加载和下拉刷新
    [self addHeader];
    [self addFooter];
    
    //菊花
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.HUD.labelText = @"加载中";
    [self.HUD show:YES];
    
    //网络数据请求
    [self getData:1];
    
}
//区
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
//row
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.videoArray.count;
}
//布局item
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //直接从系统的重用池中取item
    VideoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    cell.videoM = [self.videoArray objectAtIndex:indexPath.row];
    //cell动画
    cell.layer.transform = CATransform3DMakeScale(0.3, 0.3, 0.1);
    [UIView animateWithDuration:0.5 animations:^{
        
        cell.layer.transform = CATransform3DMakeScale(1, 1, 0.1);
    }];

    return cell;
}
//点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    VideoWebViewController *videoWebVC = [[VideoWebViewController alloc] init];
    videoWebVC.videoM = [self.videoArray objectAtIndex:indexPath.row];
    [self.navigationController pushViewController:videoWebVC animated:YES];
    [videoWebVC release];
}

//网络数据请求
- (void)getData:(NSInteger)number;
{

    NSString *urlStr = [NSString stringWithFormat:@"http://api.tudou.com/v6/video/search?app_key=90256538062520f9&format=json&kw=侣行&pageNo=%ld&pageSize=100&orderBy=createTime",number];
    self.next_Page++;

    NSString *urlEcod = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; //若请求的网址有中文,需转码
    
    NSLog(@"url==========%@",urlEcod);
    [HTTPTool get:urlEcod body:nil httpResult:HTTP success:^(id result) {
        if (self.isUpLoading == NO) {
            [self.videoArray removeAllObjects];
        }
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:result options:0 error:nil];
        

        NSMutableArray *array = [dic objectForKeyedSubscript:@"results"];

            for (NSMutableDictionary *dic2 in array) {
                VideoModel *videoM = [[VideoModel alloc] init];
                [videoM initWithDic:dic2];
                NSLog(@"videoM ========== %@",videoM.title);
                [self.videoArray addObject:videoM];
                [videoM release];
            }
        [self.collectionView headerEndRefreshing];
        [self.collectionView footerEndRefreshing];
        [self.collectionView reloadData];
        [self.HUD removeFromSuperview];

        
    } failure:^(NSError *error) {
        

    }];
}
//刷新
- (void)addHeader
{
    //    __unsafe_unretained typeof(self) vc = self;
    __block VideoViewController *vc = self;
    
    // 添加下拉刷新头部控件
    [self.collectionView addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        vc.next_Page = 1;
        vc.isUpLoading = NO;//标记为下拉操作
        [vc getData:1];//重新请求数据
        
    }];
 
}
- (void)addFooter
{
    //    __unsafe_unretained typeof(self) vc = self;
    __block VideoViewController *vc = self;
    // 添加上拉刷新尾部控件
    [self.collectionView addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        vc.isUpLoading = YES;//标记为上拉操作
        [vc getData:vc.next_Page];//请求更多数据
        
    }];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
